//
//  InspectionGtasksTaskTableVC.m
//  Estate
//
//  Created by wangdongdong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define CELL_HEIGHT 46.0f
#import "InspectionGtasksTaskTableVC.h"
#import "addPatrolTaskTableVC.h"
#import "PatrolTaskTableViewController.h"
#import "NewInspectionTextCell.h"

@interface InspectionGtasksTaskTableVC ()<UITableViewDelegate, UITableViewDataSource>

// 表格
@property (strong, nonatomic) UITableView *tableView;

// 数据
@property (strong, nonatomic) NSMutableArray *DataArray;

// 提示label(没有任务)
@property (strong, nonatomic) UILabel *taskLabel;

@end


@implementation InspectionGtasksTaskTableVC

-(UITableView *)tableView{
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    
    [self initDataSource];
    if (!(self.DataArray.count > 0) && !self.taskLabel) {
        [self noTask];
    }
    [self createView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadInspectItemList) name:@"editInspect" object:nil];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(reloadInspectItemList) name:@"Refresh_xjzz" object:nil];
}

-(void)reloadInspectItemList {
    [self.DataArray removeAllObjects];
    [self initDataSource];
    [self.tableView reloadData];
    
    if (!(self.DataArray.count > 0) && !self.taskLabel) {
        [self noTask];
    }else{
        if(self.taskLabel){
            [self.taskLabel removeFromSuperview];
        }
    }
}

// 提示信息
- (void)noTask {
    UILabel *label = [[UILabel alloc] init];
    self.taskLabel = label;
    label.text = @"您已没有要巡检的任务了!!!";
    label.font = [UIFont systemFontOfSize:25];
    [label sizeToFit];
    
    CGPoint point;
    point.x = 375 * BIZ / 2;
    point.y = self.view.center.y - 100;
    label.center = point;
    [self.view addSubview:label];
}

// 创建添加btn
- (void)createView {
    UIButton *addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [self.view addSubview:addBtn];
    // 添加验收
    [addBtn addTarget:self action:@selector(addContent) forControlEvents:UIControlEventTouchUpInside];
}

// 添加临时巡检任务
- (void)addContent {
    // 获取任务状态
    NSString *state = [self checkTaskState];
    
    if ([state isEqualToString:@"3"] || [state isEqualToString:@"4"] || [state isEqualToString:@"5"]) {
        [LSUtility showToastWithMessage:@"组长已经汇总过该任务！不可以继续新建巡检项！" inView:self.navigationController.view Andtime:1.];
        
    } else {
        addPatrolTaskTableVC *addPTVC = [[addPatrolTaskTableVC alloc] init];
        addPTVC.IPID = self.IPID;
        [self.navigationController pushViewController:addPTVC animated:YES];
    }
}

// 查看当前任务的状态
- (NSString *)checkTaskState {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS WHERE ID = '%@'", self.IPID];
    FMResultSet *result = [db executeQuery:sql];
    
    NSString *state;
    while ([result next]) {
        state = [result stringForColumn:@"INSPECT_STATE"];
    }
    [db close];
    return state;
}

// 初始化数据
- (void)initDataSource {
    // 初始化数据源
    _DataArray=[[NSMutableArray alloc] init];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找所有的一级巡检项ID
    NSArray *firstArr = [self getInspectItem];
    
    // 查找有巡检项的数据
    for (int i = 0; i < firstArr.count; i++) {
        NSDictionary *dic = firstArr[i];
        // 查找二级巡检项数据
        NSMutableArray *secondArr = [self getSecondData:dic[@"ID"]];
        
        // 查找只有一级巡检项的巡检
        NSString *IUISql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@' AND INSPECT_ITEM_ID = '%@' AND INSPECT_CURRENT_STATE = '1'", self.IPID, USERID, dic[@"ID"]];
        FMResultSet *IUIResult = [db executeQuery:IUISql];
        
        while ([IUIResult next]) {
            NSString *inspectUserItemID = [IUIResult stringForColumn:@"ID"];
            
            //先查询巡检条数 如果大于2那就巡检过  解决检查过 却没有更改在状态的bug
            
            NSString *sql_check=[NSString stringWithFormat:@"select id FROM INSPECT_PROCESS_RECORD where inspect_user_item_id='%@'",inspectUserItemID];
            
            NSMutableArray *checkArray=[NSMutableArray array];
            
            FMResultSet *result_check=[db executeQuery:sql_check];
            
            while ([result_check next]) {
                NSString *checkid=[result_check stringForColumn:@"ID"];
                [checkArray addObject:checkid];
            }
            
            if(checkArray.count==1){
                // 巡检项状态
                NSString *state = [IUIResult stringForColumn:@"INSPECT_CURRENT_STATE"];
                // 每条巡检项数据
                NSDictionary *rowDic = @{@"INSPECT_USER_ITEM_ID":inspectUserItemID, @"SECOND_TITLE":dic[@"NAME"], @"STATE":state};
                [secondArr addObject:rowDic];
            }
        }
        
        if (secondArr.count > 0) {
            // 每组任务数据
            NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:dic[@"NAME"], @"FIRST_ITEM", [NSString stringWithFormat:@"%lu", (unsigned long)secondArr.count], @"COUNT", secondArr, DIC_ARARRY, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
            // 将字典加入数组
            [self.DataArray addObject:firstDic];
        }
    }
    
    // 查找没有巡检项的数据
    NSString *nullIUISql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_ITEM_ID = '' AND INSPECT_CURRENT_STATE = '1' AND INSPECT_USER_ID = '%@'", self.IPID, USERID];
    FMResultSet *nullIUIResult = [db executeQuery:nullIUISql];
    
    // 二级巡检项数据
    NSMutableArray *secondArr2 = [NSMutableArray array];
    while ([nullIUIResult next]) {
        // 用户巡检项ID
        NSString *inspectUserItemID = [nullIUIResult stringForColumn:@"ID"];
        
        //先查询巡检条数 如果大于2那就巡检过  解决检查过 却没有更改在状态的bug
        
        NSString *sql_check=[NSString stringWithFormat:@"select id FROM INSPECT_PROCESS_RECORD where inspect_user_item_id='%@'",inspectUserItemID];
        
        NSMutableArray *checkArray=[NSMutableArray array];
        
        FMResultSet *result_check=[db executeQuery:sql_check];
        
        while ([result_check next]) {
            NSString *checkid=[result_check stringForColumn:@"ID"];
            [checkArray addObject:checkid];
        }
        if(checkArray.count==1){
            // 额外巡检名称
            NSString *tionalName = [nullIUIResult stringForColumn:@"INSPECT_ADDTIONAL_NAME"];
            // 巡检项状态
            NSString *state = [nullIUIResult stringForColumn:@"INSPECT_CURRENT_STATE"];
            // 每条巡检项数据
            NSDictionary *rowDic = @{@"INSPECT_USER_ITEM_ID":inspectUserItemID, @"SECOND_TITLE":tionalName, @"STATE":state};
            [secondArr2 addObject:rowDic];
        }
    }
    
    if (secondArr2.count > 0) {
        // 每组任务数据
        NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"其他", @"FIRST_ITEM", [NSString stringWithFormat:@"%lu", (unsigned long)secondArr2.count], @"COUNT", secondArr2, DIC_ARARRY, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
        // 将字典加入数组
        [self.DataArray addObject:firstDic];
    }
    
    [db close];
}

// 查找所有的一级巡检项ID
- (NSArray *)getInspectItem {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE PARENT_ID = '0'"];
    FMResultSet *result = [db executeQuery:sql];
    
    // ID数组
    NSMutableArray *IDArr = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        NSString *name = [result stringForColumn:@"INSPECT_NAME"];
        
        NSDictionary *dic = @{@"ID":ID, @"NAME":name};
        [IDArr addObject:dic];
    }
    [db close];
    return IDArr;
}

-(NSString *)getPARENTNameWithPARENT_ID:(NSString *)PARENT_ID ids:(NSMutableArray *)ids{
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql_check=[NSString stringWithFormat:@"select * FROM INSPECT_ITEM where PARENT_ID='%@' ORDER BY CREATE_TIME DESC",PARENT_ID];
    FMResultSet *result_check=[db executeQuery:sql_check];
    
    NSString *checkid;
    NSString *name;
    BOOL isyou = NO;
    while ([result_check next]) {
        isyou = YES;
        checkid=[result_check stringForColumn:@"ID"];
        NSLog(@"%@",checkid);
        name=[result_check stringForColumn:@"INSPECT_NAME"];
        [ids addObject:checkid];
        [self getPARENTNameWithPARENT_ID:checkid ids:ids];
    }
    [db close];

    
    return checkid;
    
}
// 查找属于当前一级巡检项的二级巡检项
- (NSMutableArray *)getSecondData:(NSString *)parentID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //此处应该直接查出三级巡检项即最子层
//    NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@' AND INSPECT_CURRENT_STATE = '1' AND INSPECT_ITEM_ID IN (SELECT ID FROM INSPECT_ITEM WHERE PARENT_ID = '%@')", self.IPID, USERID, parentID];
    NSMutableArray *ids = [NSMutableArray array];
    [self getPARENTNameWithPARENT_ID:parentID ids:ids];
    //作为条件
    NSString *inspectStr=[LSUtility dictionaryToJson_2:ids];
    //转化为sql条件
    NSString *inspectCon=[LSUtility SymbolConversion:inspectStr];

     NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_USER_ID = '%@' AND INSPECT_CURRENT_STATE = '1' AND INSPECT_ITEM_ID IN %@  ", self.IPID, USERID,inspectCon];
    FMResultSet *IPRresult = [db executeQuery:IPRStr];

    // 二级巡检项名称数组
    NSMutableArray *inspectNameArr = [NSMutableArray array];
    while ([IPRresult next]) {
        
        // 用户巡检项ID
        NSString *inspectUserItemID = [IPRresult stringForColumn:@"ID"];

        //先查询巡检条数 如果大于2那就巡检过  解决检查过 却没有更改在状态的bug
        
        NSString *sql_check=[NSString stringWithFormat:@"select id FROM INSPECT_PROCESS_RECORD where inspect_user_item_id='%@'",inspectUserItemID];
        
        NSMutableArray *checkArray=[NSMutableArray array];
        
        FMResultSet *result_check=[db executeQuery:sql_check];
        
        while ([result_check next]) {
            NSString *checkid=[result_check stringForColumn:@"ID"];
            [checkArray addObject:checkid];
        }
        if(checkArray.count==1){
            // 二级巡检项ID
            NSString *ispectItemID = [IPRresult stringForColumn:@"INSPECT_ITEM_ID"];
            
            // 巡检项状态
            NSString *state = [IPRresult stringForColumn:@"INSPECT_CURRENT_STATE"];
            // 根据二级巡检项ID查找巡检项实体表数据
            NSString *IIStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE ID = '%@'", ispectItemID];
            FMResultSet *IIresult = [db executeQuery:IIStr];
            
            while ([IIresult next]) {
                // 二级巡检项名称
                NSString *inspectName = [IIresult stringForColumn:@"INSPECT_NAME"];
                // 每条巡检项数据
                NSDictionary *rowDic = @{@"INSPECT_USER_ITEM_ID":inspectUserItemID, @"SECOND_TITLE":inspectName, @"STATE":state};
                [inspectNameArr addObject:rowDic];
            }

        }

        
        
        }
    [db close];
    return inspectNameArr;
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _DataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = [_DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46 * BIZ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section = indexPath.section;
    long row = indexPath.row;
    
    // 得到改组下信息
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics = array[row];

    return [self cellHeightWithObj:dics[@"SECOND_TITLE"]];;
}


- (CGFloat)cellHeightWithObj:(NSString *)string{
    CGFloat cellHeight = 60;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - 100;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=60){
        return 60;
    }else{
        return cellHeight;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    // 得到改组下信息
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics = array[row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    // 列表标题
    cell.title.text = dics[@"SECOND_TITLE"];
    cell.title.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:16.*BIZ];
    
    if ([dics[@"STATE"] isEqualToString:@"1"]) {
        cell.state.text = @"待巡检";
        
    } else if ([dics[@"STATE"] isEqualToString:@"2"]) {
        cell.state.text = @"待汇总";
        
    } else if ([dics[@"STATE"] isEqualToString:@"3"]) {
        cell.state.text = @"待整改";
        
    } else if ([dics[@"STATE"] isEqualToString:@"4"]) {
        cell.state.text = @"待审阅";
        
    } else if ([dics[@"STATE"] isEqualToString:@"5"]) {
        cell.state.text = @"已完成";
    }
    
//    // 图片
//    UIImage *icon = [LSUtility createImageWithColor:[UIColor colorWithRed:0.78 green:0.26 blue:0.09 alpha:1.00]];
//    CGSize itemSize = CGSizeMake(4, 70 * BIZ);
//    UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);
//    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
//    [icon drawInRect:imageRect];
    
//    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    return cell;
}

#pragma mark - 点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section=indexPath.section;
    NSInteger row=indexPath.row;
    
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics = array[row];
    
    PatrolTaskTableViewController *detailVC = [[PatrolTaskTableViewController alloc] init];
    detailVC.IPID = self.IPID;
    detailVC.IUIID = dics[@"INSPECT_USER_ITEM_ID"];
    NSLog(@"该用户巡检项id:%@",dics[@"INSPECT_USER_ITEM_ID"]);
    detailVC.firstInspectItem = dic[@"FIRST_ITEM"];
    detailVC.secondInspectItem = dics[@"SECOND_TITLE"];
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSString *titleStr = [NSString stringWithFormat:@"%@ (%@条)", dic[@"FIRST_ITEM"], dic[@"COUNT"]];
    [eButton setTitle:titleStr forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.*BIZ];
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,30)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(5,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

# pragma mark -- 内部调用
//返回指定节是否是展开的
-(int)isExpanded:(long)section{
    NSDictionary *dic = [_DataArray objectAtIndex:section];
    int expanded = [[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender {
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section {
    NSMutableDictionary *dic = [_DataArray objectAtIndex:section];
    int expanded = [[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
